﻿/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * 选择编码为UTF-8
 * 终于把所有的编码都调整好了，在google svn的服务器和本地的eclipse上面都没有出现中午注释乱码
 */
package com.android.RobotController;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;


import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This is the main Activity that displays the current chat session.
 */
public class MainActivity extends Activity {
    // Debugging
    private static final String TAG = "MainActivity";
    private static final boolean D = true;

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;

    // Layout Views
    private TextView mTitle;
    private ListView mConversationView; //显示 蓝牙通信信息的控件

    //机器人行为控制按钮定义
    private Button mButton1;
    private Button mButton2;
    private Button mButton3;
    private Button mButton4;
    private Button mButton5;
    private Button mButton6;
    private Button mButton7;
    private Button mButton8;
    private Button mButtonStart;
    
    //按钮的时间监听对象
    MyButtonListener mButtonListener;
    
    private boolean isStart =false;
    
    //显示预览和处理预览的控件，录像对象
	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;
    private File myRecAudioFile; 
    private File dir;
    private MediaRecorder myMediaRecorder;   
    private boolean isRecording = false; 
    
    // Name of the connected device
    private String mConnectedDeviceName = null;
    // Array adapter for the conversation thread
    private ArrayAdapter<String> mConversationArrayAdapter;
    // String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the chat services
    private BluetoothChatService mChatService = null;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(D) Log.e(TAG, "+++ ON CREATE +++");
        
        Log.i("cyy","onCreat....");

        // Set up the window layout
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);    
        
         // Set up the custom title
         mTitle = (TextView) findViewById(R.id.title_left_text);
         mTitle.setText(R.string.app_name);
         mTitle = (TextView) findViewById(R.id.title_right_text);

        //机器人行为控制按钮。。。设置长按的事件监听
       mButton1 = (Button)findViewById(R.id.button1);
       mButton2 = (Button)findViewById(R.id.button2);
       mButton3 = (Button)findViewById(R.id.button3);
       mButton4 = (Button)findViewById(R.id.button4);
       mButton5 = (Button)findViewById(R.id.button5);
       mButton6 = (Button)findViewById(R.id.button6);
       mButton7 = (Button)findViewById(R.id.button7);
       mButton8 = (Button)findViewById(R.id.button8);
       mButtonStart = (Button)findViewById(R.id.buttonStart);
       
       mButtonListener = new MyButtonListener();
       
       mButton1.setOnLongClickListener(mButtonListener);
       mButton2.setOnLongClickListener(mButtonListener);
       mButton3.setOnLongClickListener(mButtonListener);
       mButton4.setOnLongClickListener(mButtonListener);
       mButton5.setOnLongClickListener(mButtonListener);
       mButton6.setOnLongClickListener(mButtonListener);
       mButton7.setOnLongClickListener(mButtonListener);
       mButton8.setOnLongClickListener(mButtonListener);
       mButtonStart.setOnLongClickListener(mButtonListener);
               
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        
        
        //设置预览控件
        mSurfaceView = (SurfaceView)this.findViewById(R.id.SurfaceView01); 
        mSurfaceHolder = mSurfaceView.getHolder();     
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);  
        //生成录像器对象
        myMediaRecorder = new MediaRecorder();
        
    }
    
    
    @Override
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        // SetupBt() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the chat session
        } else {
            if (mChatService == null) SetupBt();
        }
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
              // Start the Bluetooth chat services
              mChatService.start();
            }
        }
    }
    
    private class MyButtonListener implements OnLongClickListener{
		@Override
		public boolean onLongClick(View v) {
			//TODO Auto-generated method stub
			//mTextMainState.setText("long click on button___");
			if(mChatService.getState() == BluetoothChatService.STATE_CONNECTED)
	      {
			String message = null;
			switch( v.getId() )
			{
				case R.id.button1:
					message = "1";
				break;
				case R.id.button2:
					message = "2";
				break;
				case R.id.button3:
					message = "3";
				break;
				case R.id.button4:
					message = "4";
				break;
				case R.id.button5:
					message = "5";
				break;
				case R.id.button6:
					message = "6";
				break;				
				case R.id.button7:
					message = "7";
				break;
				case R.id.button8:
					message = "8";
					break;	
				case R.id.buttonStart:
				{
					   if(isStart)
					   {
						  isStart = false;
						  message = "stop";
						  mButtonStart.setText("START");
					   }else
					   {
						  isStart = true;
						  message = "start";
						  mButtonStart.setText("STOP");
					   }
				    break;
				}
					}
			 if(isStart)
			 {
				 sendMessage(message);
			 }	
	      }//endif
			
			return false;
		}
    	
    }
    
    //函数SetpupBt()为蓝牙串口通信做些准备性的工作
    private void SetupBt() {
        Log.d(TAG, "SetupBt()");

        //显示蓝牙通信内容的控件
        // Initialize the array adapter for the conversation thread
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
        mConversationView = (ListView) findViewById(R.id.Mesgview);
        mConversationView.setAdapter(mConversationArrayAdapter);
        
        // Initialize the BluetoothChatService to perform bluetooth connections
        mChatService = new BluetoothChatService(this, mHandler);

        // Initialize the buffer for outgoing messages
        mOutStringBuffer = new StringBuffer("");
    }
    //函数SetupRec()为视频录像做些准备性的工作，主要是设置参数
    public void SetupRec() 
    {
        File defaultDir = Environment.getExternalStorageDirectory();
        String path = defaultDir.getAbsolutePath()+File.separator+"myvideo"+File.separator;//创建文件夹存放视频
        dir = new File(path);
        if(!dir.exists()){
        	dir.mkdir();
        }        
		new DateFormat();
		myRecAudioFile = new File("/sdcard/myvideo/"
				+ DateFormat.format("yyyyMMdd_hhmmss",
						Calendar.getInstance(Locale.CHINA)) + ".3gp");
    	
        try {
            //myRecAudioFile = File.createTempFile("video", ".3gp",dir);//创建临时文件
        	myRecAudioFile.createNewFile();
        }catch(IOException e)
        {
        	e.printStackTrace();
        }
        
        
        try{	
        	//一定要注意参数的设置顺序，否则
            myMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());//预览     
            myMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//视频源
            myMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); //录音源为麦克风
            myMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//输出格式为3gp
            myMediaRecorder.setVideoSize(640, 480);//视频的分辨率
            //myMediaRecorder.setVideoSize(480, 320);
            myMediaRecorder.setVideoFrameRate(20);//视频帧频率
            myMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);//视频编码
            myMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//音频编码
            //myMediaRecorder.setMaxDuration(MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED);//最大期限设置为最大
            //但是使用这个常量设置后，只能录制1秒   
            myMediaRecorder.setMaxDuration(10000000);
            myMediaRecorder.setOutputFile(myRecAudioFile.getAbsolutePath());//保存路径
            myMediaRecorder.prepare();
        } catch (IllegalStateException  e) 
        {
            e.printStackTrace();
        } catch (IOException e) 
        {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }//end_SetupRec()

    @Override
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
    }

    @Override
    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
    }

    
    //记得要释放录像机的资源，release和对象置空null
    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mChatService != null) mChatService.stop();
        if(D) Log.e(TAG, "--- ON DESTROY ---");       
        if(myMediaRecorder!=null)
        {
            myMediaRecorder.release();
            myMediaRecorder=null;
        }
    }

    private void ensureDiscoverable() {
        if(D) Log.d(TAG, "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    /**
     * Sends a message.
     * @param message  A string of text to send.
     */
    private void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }

        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            byte[] send = message.getBytes();
            mChatService.write(send);

            // Reset out string buffer to zero 
            mOutStringBuffer.setLength(0);
        }
    }


    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case BluetoothChatService.STATE_CONNECTED:
                    mTitle.setText(R.string.title_connected_to);
                    mTitle.append(mConnectedDeviceName);
                    mConversationArrayAdapter.clear();
                    break;
                case BluetoothChatService.STATE_CONNECTING:
                    mTitle.setText(R.string.title_connecting);
                    break;
                case BluetoothChatService.STATE_LISTEN:
                case BluetoothChatService.STATE_NONE:
                    mTitle.setText(R.string.title_not_connected);
                    break;
                }
                break;
            case MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                String writeMessage = new String(writeBuf);
                mConversationArrayAdapter.add("Me:  " + writeMessage);
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
                mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
                String address = data.getExtras()
                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                // Attempt to connect to the device
                mChatService.connect(device);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
                SetupBt();
            } else {
                // User did not enable Bluetooth or an error occured
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
    
//创建menu按键菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }
    
//menu按键菜单的选择函数
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.scan:
            // Launch the DeviceListActivity to see devices and do scan
            Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            return true;
        case R.id.discoverable:
            // Ensure this device is discoverable by others
            ensureDiscoverable();
            return true;
        case R.id.startRec:
        	//开始录制视频
        	if(isRecording == false)
        	{
        	  isRecording = true;
        	  SetupRec();
        	  myMediaRecorder.start();
        	}
        	return true;
        case R.id.stopRec:
        	//停止视频录制
        	if(isRecording == true)
        	{
        	 isRecording = false;
             myMediaRecorder.stop();
             myMediaRecorder.reset();
        	}
        	return true;
        }
        return false;
    }

}


/*SVNtest*/